import cloneDeep from "lodash/cloneDeep";
import { getProcessTitle, getQuery } from "./index";
import myMessage from "./message";

/**
 * 
 * @param {*} params 
 * @param {*} tplData 
 * @param {*} approveType 审批类型 类型如下：
 * Initiate 发起
 * Pass 同意
 * 
 * @param {*} type 其他类型，类型如下：
 * Draft 保存草稿
 * getstep获取发起步骤 
 * getBranchStep获取分支步骤 
 */
export default function getInitiateFormData ({
  params, 
  tplData, 
  approveType,
  type
}){
  if(!approveType){
    console.log("getInitiateFormData缺少approveType参数");
    return{};
  }
  let param = cloneDeep(params);
  let form_data = cloneDeep(tplData.form.form_data);

  //这部分数据在initiateForm.js内完成收集
  if(!param.initiater){
    param.initiater = {};
  }

  let approveForm = tplData?.__approveForm__?.[approveType];//footer区审批表单数据
  if(approveForm){//合并审批表单数据
    param = {...param, ...approveForm};//把审批表单数据合并到param

    param.initiater = {...param.initiater, ...approveForm};//把审批表单数据合并到param.initiater
    //删除不需要的脏数据
    delete param.initiater.step_cc_list;
    delete param.initiater.opinion;
    delete param.initiater.sign_id;
    delete param.initiater.process_level;

    console.log("获取类型：" + approveType + "，审批表单搜集的信息", approveForm)
  }

  //所有请求需要的公共参数
  param.form_data = {
    children: form_data.children,
    fieldSources: form_data.fieldSources,
    main: form_data.main,
    attachmentTypes: form_data.attachmentTypes
  };

  if(approveType === "Initiate"){//发起流程
    param.initiater.initiater_company_id = tplData.__approveForm__[approveType].initiater_org_id;//发起部门 为什么跟上面 initiater_org_id 取值一样？（老代码逻辑）
    param.monitor_list = tplData.ProcessInfo.WatcherName; //监控人
    param.process_info = {
      ProcessDisplayName: tplData.ProcessInfo.ProcessDisplayName,
      ProcessModuleName: tplData.ProcessInfo.ProcessModuleName
    }
    if(form_data.usedSys){//已经使用的系统字段
      param.usedSys = form_data.usedSys;
    }
    delete param.initiater_org_id
    delete param.initiater_org_name
  }

  if(["Initiate", "Pass", "Book" ,"Vote","Consult","ReplyConsult","Assigned","Terminate","AddSign","Cancel"].indexOf(approveType) > -1){//发起流程 || 同意  || 归档 ||表决 ||发起协商 ||回复协商 || 作废
    if (tplData.step_cc_list_default && tplData.step_cc_list_default.length > 0) {
      let paramStepCcList = param?.step_cc_list || [];
      param.step_cc_list = paramStepCcList.concat(tplData.step_cc_list_default);//默认的抄送人
    }
  }
  
  if(type === "Draft" || ["Initiate", "RollBack", "Pass", "Book" ,"Vote","Consult","ReplyConsult","Assigned","Terminate","AddSign","Cancel"].indexOf(approveType) > -1){//保存草稿 || 发起 || 驳回 || 同意 || 归档 ||表决 ||发起协商||回复协商 || 作废
    param.attachment_control = tplData.form.attachment_control;//附件信息
  }
  if(type === "Draft" || ["Initiate"].indexOf(approveType) > -1){//保存草稿 || 发起
    param.title = tplData.ProcessInfo.Title;
    if (params.ParentProcess) {
      param.title = getProcessTitle({
        form_data: param.form_data,
        params: params,
        tplData: tplData
      });//前端计算标题
    }
    param.monitors = tplData.ProcessInfo.Monitors;//监控人
    if(tplData.ProcessInfo.newMonitors){//如果存在新的监控人，则改变发起时提交的监控人信息
      param.monitors = tplData.ProcessInfo.newMonitors;
    }
  }

  if(type === "Draft" || ["Initiate", "Pass", "Book" ,"Vote","Consult","ReplyConsult","Assigned","Terminate","AddSign", "Cancel"].indexOf(approveType) > -1){//保存草稿 || 发起 || 同意 || 归档 ||表决||发起协商||回复协商
    param.relation_process = tplData.RelationProcess.RelationProcessList;//相关流程
    let processTitle = param.title || tplData.ProcessInfo.Title;//草稿、发起取第一个，其他类型取tpldata上的
    if (processTitle.length > 200) {//标题校验
      myMessage.info({
          icon: null,
          //title:"流程详情",
          width: 400,
          centered: true,
          okText:"关闭",
          content: "流程名称不能超过200字符"
      });
      return false;//校验没通过返回false
    }
  }

  if(type === "Draft" || ["Initiate", "Pass", "RollBack", "Book" ,"Vote","Consult","ReplyConsult","Assigned","Terminate","AddSign","Cancel"].indexOf(approveType) > -1){//保存草稿 || 发起 || 同意 || 驳回 || 归档 || 表决||发起协商||回复协商 || 作废
    param._prc_name_ = tplData.ProcessInfo.Title;
  }

  if(type === "getstep" || approveType === "Initiate"){//获取发起步骤 || 发起流程
    //子流程发起步骤
    if (params.IsSubProc) {
      param.initiater.initiater_name = tplData.NodeInfo.auditor_name;
      param.initiater.initiater_id = tplData.NodeInfo.auditor_id;
    }
  }

  delete param.data_control;
  return param;
}


export function getApproveDraftData({
  params, 
  tplData
}){

  let form_data = cloneDeep(tplData.form.form_data);
  var action = tplData.__approveType__ || "";

  let returnData = {
    proc_id: tplData.ProcessInfo.ProcessGuid,
    node_id: tplData.NodeInfo.node_id || getQuery().node_id,
    form_data: {
        children: form_data.children,
        main: form_data.main,
        fieldSources: form_data.fieldSources
    },
    delete_attachments: params.delete_attachments,//记录删除附件
    file_sort: params.file_sort,//附件排序信息
    approve: {
      action: action,// 审批操作
      add_sign_after: [],// 加签后是否需要确认
      add_sign_users: [],// 加签
      archived_directory_id: "",// 归档目录
      assigned: [],// 交办
      initiater_org_id: "",// 审批组织
      opinion: {},// 审批意见
      radio_back: "",// 打回到
      roll_back_type: "",// 驳回是否重走
      sign_id: '',// 签章
      step_cc_list: [],// 抄送人
      step_id: null,// 驳回步骤
      to: [],// 协商
      voted_status: "",// 表决
    }
  };
  returnData.approve = {
    ...returnData.approve,
    ...tplData.approve//后端初始审批值
  }

  if(tplData.__approveForm__){//存在表单
    Object.keys(tplData.__approveForm__).forEach(function(approveType){
      var approveFormData = cloneDeep(tplData.__approveForm__[approveType]);
      if(!returnData.approve.opinion){
        returnData.approve.opinion = {};
      }
      returnData.approve.opinion[approveType] = approveFormData.opinion;//审批意见
      
      delete approveFormData.opinion;//删除审批意见，审批意见不能用合并的方式覆盖到要提交的数据上
      returnData.approve = {
        ...returnData.approve,
        ...approveFormData
      }//把各审批表单数据覆盖一遍
    })
  };

  if(tplData.__approveFormCommonData__){//存在审批表单公共字段信息
    returnData.approve = {
      ...returnData.approve,
      ...tplData?.__approveFormCommonData__
    }//把审批表单公共字段信息覆盖到需要提交的数据上
  }

  var reInitiate = false;
  tplData.ApproveButtons.forEach(function(btn) {
      if (btn['OperationCode'] == 'Pass' && btn['ButtonIcon'] == 'icon-faqi') {
          reInitiate = true;
      }
  })
  if(reInitiate){
    returnData.relation_process = tplData.RelationProcess.RelationProcessList;
  }
  
  return returnData;
}

//获取审批表单数据，包括发起 和 审批中的表单数据
export function getApproveFormData({
  tplData
}){
  if(tplData.__approveType__){//当前审批类型
    return tplData?.__approveForm__?.[tplData.__approveType__];//获得审批表单区数据
  }else{
    console.warn("tplData.__approveType__不存在");
    return {};//如果没有审批类型，返回空对象，兼容报错
  }
}